from fastapi import APIRouter, HTTPException
from typing import Dict, Any
from datetime import datetime
from websocket.mock_data import MockDataGenerator
from config.settings import DEFAULT_SYMBOL
from cache.order_cache import order_cache

router = APIRouter()
mock_generator = MockDataGenerator()

@router.get("/api/v2/mix/market/ticker")
async def get_ticker(instId: str = DEFAULT_SYMBOL):
    try:
        mock_data = mock_generator.generate_ticker_data(instId, "SUSDT-FUTURES")
        return {
            "code": "0",
            "msg": "",
            "data": mock_data["data"]
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/api/v2/mix/order/place-order")
async def place_order(order: Dict[str, Any]):
    try:
        # 生成以111开头的orderId和clientOid
        ts = int(datetime.now().timestamp() * 1000)
        oid = f"111{str(ts)[-10:]}"  # 111+后10位时间戳，保证长度
        request_time = ts
        # # 刷新订单缓存
        # try:
        #     order_cache.refresh()
        # except Exception as e:
        #     # 记录错误但不影响API响应
        #     from utils.logger import logger
        #     logger.error(f"[API] 刷新订单缓存失败: {str(e)}")

        return {
            "code": "00000",
            "msg": "success",
            "requestTime": request_time,
            "data": {
                "clientOid": oid,
                "orderId": oid
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/api/v2/mix/order/place-plan-order")
async def place_plan_order(order: Dict[str, Any]):
    try:
        # 生成以222开头的orderId和clientOid，用于区分计划委托单
        ts = int(datetime.now().timestamp() * 1000)
        oid = f"222{str(ts)[-10:]}"  # 222+后10位时间戳，保证长度
        request_time = ts
        # # 刷新订单缓存
        # try:
        #     order_cache.refresh()
        # except Exception as e:
        #     # 记录错误但不影响API响应
        #     from utils.logger import logger
        #     logger.error(f"[API] 刷新订单缓存失败: {str(e)}")

        return {
            "code": "00000",
            "msg": "success",
            "requestTime": request_time,
            "data": {
                "clientOid": oid,
                "orderId": oid
            }
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/api/v2/mix/order/cancel-all-orders")
async def cancel_all_orders():
    try:
        # 示例数据
        result = {
            "code": "00000",
            "data": {
                "successList": [
                    {
                        "orderId": "121211212122",
                        "clientOid": "BITGET#121211212122"
                    }
                ],
                "failureList": [
                    {
                        "orderId": "232",
                        "clientOid": "321342",
                        "errorMsg": "notExistend"
                    }
                ]
            },
            "msg": "success",
            "requestTime": int(datetime.now().timestamp() * 1000)
        }
        # 刷新订单缓存
        # try:
        #     order_cache.refresh()
        # except Exception as e:
        #     # 记录错误但不影响API响应
        #     from utils.logger import logger
        #     logger.error(f"[API] 刷新订单缓存失败: {str(e)}")

        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/api/v2/mix/account/accounts")
async def get_accounts(productType: str = "USDT-FUTURES"):
    try:
        result = {
            "code": "00000",
            "msg": "success",
            "requestTime": int(datetime.now().timestamp() * 1000),
            "data": [{"marginCoin":"SUSDT","locked":"0","available":"3169.49295688","crossedMaxAvailable":"3097.35372896","isolatedMaxAvailable":"3097.35372896","maxTransferOut":"3063.04632698","accountEquity":"3203.80035886","usdtEquity":"3203.800358861651","btcEquity":"0.033700745753","crossedRiskRate":"0.003781179426","unrealizedPL":"34.307401974921","coupon":"0","crossedUnrealizedPL":"","isolatedUnrealizedPL":"","grant":"","unionTotalMargin":"3203.80035886","unionAvailable":"3097.35372896","unionMm":"12.114144","assetList":[],"assetMode":"single","isolatedMargin":"0","crossedMargin":"106.4466299"}]
        }
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e)) 